package com.zzyl.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?";

    @Value("${zzyl.framework.wechat.appId}")
    private String appId;

    @Value("${zzyl.framework.wechat.appSecret}")
    private String appSecret;

    @Override
    public String getOpenId(String code){

        Map<String, Object> map = getAppConfig();

        map.put("js_code", code);
        String res = HttpUtil.get(REQUEST_URL,map);
        JSONObject jsonObject = JSONUtil.parseObj(res);

        if (ObjectUtil.isNotEmpty(jsonObject.get("errcode"))){ //errorcode 有值的时候会报错
            throw new RuntimeException("获取open Id 失败");
        }
        String openid = (String)jsonObject.get("openid");
        return openid;
    }

    @Override
    public String getPhone(String phoneCode){
        //1.获取access_token
        Map<String, Object> map = getAppConfig();
        String res = HttpUtil.get(TOKEN_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(res);
        String accessToken = (String) jsonObject.get("access_token");

        //2.accessToken 获取电话号码
        Map<String, Object> phonemap = new HashMap<>();
//        map.put("access_token",accessToken);
        phonemap.put("code",phoneCode);
        String result = HttpUtil.post(PHONE_URL + "access_token=" + accessToken,JSONUtil.toJsonStr(phonemap));
        JSONObject json = JSONUtil.parseObj(result);
        if (!json.get("errcode").equals(0)){
            throw new RuntimeException("获取电话号码错误");
        }

        JSONObject phoneInfo = (JSONObject)json.get("phone_info");
        String phoneNumber = (String)phoneInfo.get("phoneNumber");

        return phoneNumber;
    }

    /**
     * 公共方法获得appid + appsecret
     * @return
     */
    private Map<String, Object> getAppConfig() {
        Map<String, Object> map = new HashMap<>();
        map.put("appid",appId);
        map.put("secret",appSecret);
        return map;
    }

}











